const useStorage = ($storage:any) => {
  /**
   * 根据 key 值获取储存在 storage 中的值
   * @param key storage key
   */
  const get = (key: string) => {
    let value = $storage.getItem(key)
    try {
      value = JSON.parse(value)
      return value
    } catch {
      return value
    }
  }

  /**
   * 根据 key 值向 storage 中储存值
   * @param key storage key
   * @param value 需要储存在 storage 中的值
   */
  const set = (key: string, value: any) => $storage.setItem(key, value ? JSON.stringify(value) : value)

  /**
   * 根据 key 值移除储存在 storage 中的值
   * @param key storage key
   */
  const remove = (key: string) => $storage.removeItem(key)

  return {
    get,
    set,
    remove,
  }
}

const SessionStorageService = useStorage(window.sessionStorage || sessionStorage)
const LocalStorageService = useStorage(window.localStorage || localStorage)

export {
  SessionStorageService,
  LocalStorageService,
}
